﻿using Bnbjoy.Domain.Abstract;
using Bnbjoy.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bnbjoy.Domain.Concrete
{
    public class MobileCaptchaRepository : IMobileCaptchaRepository
    {
        public async Task<MobileCaptcha> FindByNumber(string num)
        {
            using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
            {
                return await bnbjoyBackendDbEntities.MobileCaptchas.AsNoTracking().Where(c => c.MobileNumber == num).FirstOrDefaultAsync();
            }
        }

        public async Task<bool> Insert(MobileCaptcha mobileCaptcha)
        {
            using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
            {
                using (var transaction = bnbjoyBackendDbEntities.Database.BeginTransaction())
                {
                    try
                    {
                        var existingMobile = await bnbjoyBackendDbEntities.MobileCaptchas.AsNoTracking().Where(c => c.MobileNumber == mobileCaptcha.MobileNumber).FirstOrDefaultAsync();
                        if (existingMobile != null)
                        {
                            //验证码发放时间加1分钟 > 当前时间，那么说明还不能重新获取，直接返回false
                            if (existingMobile.IssuedTime.AddMinutes(1) > DateTime.Now) 
                            {
                                return false;
                            }
                            else
                            {
                                var dResult = await Delete(existingMobile);
                            }
                        }

                        bnbjoyBackendDbEntities.MobileCaptchas.Add(mobileCaptcha);
                        bool iResult = await bnbjoyBackendDbEntities.SaveChangesAsync() > 0;
                        transaction.Commit();
                        return iResult;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        return false;
                    }
                }
            }
        }

        public async Task<bool> Delete(MobileCaptcha mobileCaptcha) 
        {
            try
            {
                using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
                {
                    bnbjoyBackendDbEntities.MobileCaptchas.Attach(mobileCaptcha);
                    bnbjoyBackendDbEntities.MobileCaptchas.Remove(mobileCaptcha);
                    return await bnbjoyBackendDbEntities.SaveChangesAsync() > 0;
                }
            }
            catch (Exception ex) 
            {
                return false; 
            }
        }

    }
}
